//
//  LWComposeViewController.swift
//  Microblog
//
//  Created by Roman on 17/1/14.
//  Copyright © 2017年 Roman. All rights reserved.
//

import UIKit
import SVProgressHUD
enum weiboType : Int{
    case Photo = 0
    case AtSome
    case Topic
    case Emoticon
    case More
}

class LWComposeViewController: UIViewController {

    //关闭
    func close() {
        textView.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    //发布微博
    @objc private func send() {
        
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //guard 来判断网络请求问题
            guard let accesstoken = LWUserAccountViewModel.shard.access_token else {
                return
            }
            //status  要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
            let parameters:[String : String] = ["access_token" : accesstoken,
                                                "status" : textView.text]
        
        //判断是否有图片
        if picSelector.images.count == 0 {
            //没有图片
            HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters, finished: { (response, error) in
                if error != nil
                {
                    SVProgressHUD.showError(withStatus: "发布微博失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发布成功")
            })
            
        }else{
            HMNetworkTools.shared.post(urlString, parameters: parameters, constructingBodyWith: { (fromdata) in
                //将要上传的文件转换为二进制数据 拼接到fromdata
                //withFileData: 需要上传文件的二进制数据
                //name: 调用接口对应的字段
                //fileName: 服务器以什么名字存储该文件   指定名字没有意义
                //mimeType: 上传的文件类型
                let image = self.picSelector.images.last!
                let imageDate = UIImagePNGRepresentation(image)!
                fromdata.appendPart(withFileData: imageDate, name: "pic", fileName: "XXXXXXX", mimeType: "application/octet-stream")
                
            }, progress: nil, success: { (_, response) in
                //发布微博成功
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
            }) { (_, error) in
                //发布失败
                SVProgressHUD.showError(withStatus: "发布微博失败")
                return
            }

            
            
        }
        
        
        
        
        
//        textView.endEditing(true)
//        let urlString = "https://api.weibo.com/2/statuses/update.json"
//        //guard 来判断网络请求问题
//        guard let accesstoken = LWUserAccountViewModel.shard.access_token else {
//            return
//        }
//        //status  要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
//        let parameters:[String : String] = ["access_token" : accesstoken,
//                                            "status" : textView.text]
//        
//        
//        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters) { (response, error) in
//            if error != nil {
//                SVProgressHUD.showError(withStatus: "发布微博失败")
//                return
//            }
//            //发布微博成功
//            SVProgressHUD.showSuccess(withStatus: "发布微博成功")
//            
//        }
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()
        setTextView()
        setToolBar()
        
        setSelectorVC()
        //注册通知
        registerNotification()
        

        // Do any additional setup after loading the view.
    }
    
    //实现键盘不会被遮挡住
    private func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //成为第一响应者
        textView.becomeFirstResponder()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        picSelector.view.isHidden = picSelector.images.count == 0
    }
    
    ///通知的监听方法.
    @objc private func keyboardWillChange(n:Notification){
        //print(n)
        //UIKeyboardFrameEndUserInfoKey
        let endFrame = n.userInfo![UIKeyboardFrameEndUserInfoKey]as! CGRect
        print(endFrame)
        //(0.0, 465.0, 414.0, 271.0)
        //底部toolbar能够移动
        //修改底部约束
        let offsetY = -(ScreenHeight - endFrame.origin.y)
        
        print(offsetY) //271
        //gen跟新约束
        UIView.animate(withDuration: 0.25) {
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offsetY)
            })
            //强制刷新
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    //自定义textView
    lazy var textView: UITextView = {
        let textV = UITextView()
        //textV.text = "请输入想表达的话,我将为你展现"
        textV.backgroundColor = UIColor.randomColor
        textV.textColor = UIColor.black
        textV.delegate = self
        textV.font = UIFont.systemFont(ofSize: 18)
        //实现三个按钮的滚动.
        textV.alwaysBounceVertical = true
        textV.keyboardDismissMode = .onDrag
        return textV
    }()
    //懒加载一个占位文本.来实现浅灰色的文字提示
    lazy var HoderLabel: UILabel = UILabel(text: "请输入想表达的话,我将为你展现", fontSize: 18, textColor: UIColor.lightGray)
    
    //自定义右侧按钮
    lazy var sendItem: UIBarButtonItem = {
        let  btn  = UIButton()
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white"), for: .disabled)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        //监听右侧按钮,实现发送
        btn.addTarget(self, action: #selector(send), for: .touchUpInside)
        btn.bounds.size.width = 50
        btn.sizeToFit()
        
        let barItem = UIBarButtonItem(customView: btn)
        //需要设置UIBarButtonItem 对象是否可以交互才可以生效 设置按钮无效
        barItem.isEnabled = false
        
        return barItem
    }()
    
    ///MARK: 底部按钮的监听事件
    @objc private func  weiboTypeBtnDidClick(btn: UIButton) {
        //通过枚举解决
    //需要将tag 值转换为枚举值 再进行判断
    let type = weiboType(rawValue: btn.tag )!
        print(type)
        //Optional(Microblog.weiboType.Photo)
        switch type {
        case .Photo:
            print("图片")
            //更新图片选择视图的高度约束
            //            picSelector.view.snp.updateConstraints({ (make) in
            //                make.height.equalTo(ScreenHeight / 3 * 2)
        //            })
            picSelector.userWillAddPic()
        case .AtSome:
            print("@某人")
        case .Topic:
            print("话题")
        case .Emoticon:
            print("表情")
        case .More:
            print("更多")
        
        }
    }
    
    //懒加载底部工具栏
    lazy var toolBar: UIStackView = {
        let stack = UIStackView()
        //srack 不能设置颜色
        //设置轴
        stack.axis = .horizontal
        //填充方式
        stack.distribution = .fillEqually
        
        //添加按钮的点击事件
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for (offset,imageName) in imageNames.enumerated() {
            //实例化按钮对象
            let button = UIButton()
            button.tag = offset
            button.addTarget(self, action: #selector(weiboTypeBtnDidClick(btn:)), for: .touchUpInside)
            button.setImage(UIImage(named: imageName), for: .normal)
            button.setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted)
            button.backgroundColor = UIColor(white: 0.9, alpha: 1)
            //添加按钮
            stack.addArrangedSubview(button)
        }
        
        
        return stack
    }()
    
    ///懒加载图片选择视图控制器
    lazy var picSelector: LWPictureSelectorController = {
        let flowLayout = UICollectionViewFlowLayout()
        //设置大小
        flowLayout.itemSize = CGSize(width: selectoritemWidth, height: selectoritemWidth)
        flowLayout.minimumInteritemSpacing = selectorCellMargin
        //设置insert
        flowLayout.sectionInset = UIEdgeInsetsMake(selectorCellMargin, selectorCellMargin, 0, selectorCellMargin)
        let vc = LWPictureSelectorController(collectionViewLayout: flowLayout)
        return vc
    }()

    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}


//封装一个UI界面
extension LWComposeViewController{
    
    func setSelectorVC() {
        //强引用图片选择控制器
        self.addChildViewController(picSelector)
        //添加图片选择视图控制器的根视图
        self.view.addSubview(picSelector.view)
        self.picSelector.view.isHidden = true
        picSelector.view.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(ScreenHeight/3*2)
        }
        
        //将toolBar移动到最顶层
        self.view.bringSubview(toFront: toolBar)
    }
    
    
    
    func setToolBar()  {
        self.view.addSubview(toolBar)
        
        //约束
        toolBar.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(40)
        }
        
    }
    
     func setTextView() {
       
        self.view.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.height.equalTo(ScreenHeight / 3 )
            
        }
        textView.addSubview(HoderLabel)
        
        HoderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
            // make.top.left.equalTo(textView)
        }
    }
    
     func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭",target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = sendItem
        //自定义titleView
        let titleLable = UILabel()
        titleLable.textAlignment = .center
        if let name = LWUserAccountViewModel.shard.account?.screen_name {
            let titleText = "发微博\n\(name)"
            titleLable.text = titleText
            titleLable.numberOfLines = 0
            //设置文综的大小和颜色
            //1.获取文本属性
            let strM = NSMutableAttributedString(string: titleText)
            //2.需要获取name 在titleText 范围
            let range = (titleText as NSString).range(of: name)
            //3.对应范围加属性
            strM.addAttributes([NSForegroundColorAttributeName : UIColor.orange, NSFontAttributeName: UIFont.systemFont(ofSize: 14)], range: range)
            //设置titleLabel的文本属性
            titleLable.attributedText = strM
        }else{
            titleLable.text = "发布微博"
        }
        titleLable.sizeToFit()
        navigationItem.titleView = titleLable
        
    }

    
}

extension LWComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //根据输入的状态修改占位文本和 发送按钮的状态
        sendItem.isEnabled = textView.hasText
        HoderLabel.isEnabled = textView.hasText
    }
}
